/**
 * Created with IntelliJ IDEA.
 * Description:
 * user:likai
 * Date:2023-01-16
 * Time:19:54
 */
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    class Solution {
        public String tree2str(TreeNode root) {

            StringBuffer stringbuffer = new StringBuffer();
            if (root == null) {
                return stringbuffer.toString();
            }
            child(stringbuffer, root);
            return stringbuffer.toString();
        }

        public void child(StringBuffer stringbuffer, TreeNode root) {
            if (root == null) {
                return;
            }
            stringbuffer.append(root.val);
            if (root.left != null || root.right != null) {
                stringbuffer.append('(');
                child(stringbuffer, root.left);
                stringbuffer.append(')');
            }
            if (root.right != null) {
                stringbuffer.append('(');
                child(stringbuffer, root.right);
                stringbuffer.append(')');
            }
        }

        public TreeNode buildTree(int[] preorder, int[] inorder) {
            int end = inorder.length - 1;
            TreeNode root = buildTreeChild(preorder, inorder, 0, end);
            return root;
        }

        public int find(int[] inorder, int begin, int end, int cur) {
            for (int i = begin; i <= end; i++) {
                if (inorder[i] == cur) {
                    return i;
                }
            }
            return -1;
        }

        int now = 0;

        public TreeNode buildTreeChild(int[] preorder, int[] inorder, int begin, int end) {
            if (begin > end) {
                return null;
            }
            TreeNode root = new TreeNode(preorder[now]);
            int mid = find(inorder, begin, end, root.val);
            if (mid == -1) {
                return null;
            }
            now++;
            root.left = buildTreeChild(preorder, inorder, begin, mid - 1);
            root.right = buildTreeChild(preorder, inorder, mid + 1, end);
            return root;
        }
    }
}
public class Test {
}
